package cn.skywalks.common.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Created by lupeng on 2017/7/25.
 */
public class HttpsUtil {

    private static final String HTTP = "http";
    private static final String HTTPS = "https";

    private static SSLConnectionSocketFactory sslfc = null;
    private static PoolingHttpClientConnectionManager connectionManager = null;
    private static SSLContextBuilder sslBuilder = null;

    static {
        try {
            sslBuilder = new SSLContextBuilder();
            sslBuilder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                    return true;
                }
            });
            sslfc = new SSLConnectionSocketFactory(sslBuilder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register(HTTP, new PlainConnectionSocketFactory())
                    .register(HTTPS, sslfc)
                    .build();
            connectionManager = new PoolingHttpClientConnectionManager(registry);
            connectionManager.setMaxTotal(200);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static CloseableHttpClient getHttpClient() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLSocketFactory(sslfc)
                .setConnectionManager(connectionManager)
                .setConnectionManagerShared(true)
                .build();
        return httpClient;
    }

    public static String doPost(String url, Map<String, Object> params){
        String ret = null;
        CloseableHttpResponse response = null;
        BufferedReader reader = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpsUtil.getHttpClient();
            HttpPost post = new HttpPost(url);
            HttpEntity entity = HttpUtil.params2Entity(params);
            post.setEntity(entity);
            response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == 200){
                reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            }
            ret = HttpUtil.bufferedReader2String(reader);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap();
        map.put("aaa", "lupengaaaaaa");
        String s = HttpsUtil.doPost("https://localhost/get", map);
        System.out.println(s);
    }
}
